package cn.iocoder.yudao.module.personal.service.notetag;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.ImageUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

import cn.iocoder.yudao.module.personal.controller.admin.notetag.vo.*;
import cn.iocoder.yudao.module.personal.dal.dataobject.notetag.NoteTagDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.personal.dal.mysql.notetag.NoteTagMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.personal.enums.ErrorCodeConstants.*;

/**
 * 笔记标签 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class NoteTagServiceImpl implements NoteTagService {

    @Resource
    private NoteTagMapper noteTagMapper;

    @Override
    public Integer createNoteTag(NoteTagSaveReqVO createReqVO) {
        // 插入
        NoteTagDO noteTag = BeanUtils.toBean(createReqVO, NoteTagDO.class);
        noteTagMapper.insert(noteTag);
        // 返回
        return noteTag.getId();
    }

    @Override
    public void updateNoteTag(NoteTagSaveReqVO updateReqVO) {
        // 校验存在
        validateNoteTagExists(updateReqVO.getId());
        // 更新
        NoteTagDO updateObj = BeanUtils.toBean(updateReqVO, NoteTagDO.class);
        noteTagMapper.updateById(updateObj);
    }

    @Override
    public void deleteNoteTag(Integer id) {
        // 校验存在
        validateNoteTagExists(id);
        // 删除
        noteTagMapper.deleteById(id);
    }

    private void validateNoteTagExists(Integer id) {
        if (noteTagMapper.selectById(id) == null) {
            throw exception(NOTE_TAG_NOT_EXISTS);
        }
    }

    @Override
    public NoteTagDO getNoteTag(Integer id) {
        return noteTagMapper.selectById(id);
    }

    @Override
    public PageResult<NoteTagDO> getNoteTagPage(NoteTagPageReqVO pageReqVO) {
        return noteTagMapper.selectPage(pageReqVO);
    }

    @Override
    public String getqrcode(String floorno,String floorType, HttpServletResponse resp) {
        if("-1".equals(floorno)){
            floorno = "0";
        }

        if("-2".equals(floorno)){
            floorno = "-1";
        }
        //String workId = "1369553087085748225";
        String workId = "1363027960881864705";

        String elevId = "1126613152363455";
        /*if("2".equals(floorType)){
            elevId = "7794212634651573";
            workId = "1363027960881864705";
        }*/

        floorno = String.valueOf(Integer.parseInt(floorno)+2);
        JSONObject sendData = new JSONObject();
        sendData.put("elevId", elevId);
        sendData.put("workId", workId);
        sendData.put("qrType", "");
        sendData.put("floorno", floorno);
        HttpResponse httpResponse = HttpUtil.createPost("http://111.14.222.51:9001/cardfront/v2/qr/getqrcode")
                .body(sendData.toJSONString(), "application/json").execute();
        System.out.println(httpResponse.body());
        String resultStr = httpResponse.body();
        if(StringUtils.isBlank(resultStr)){
            return "";
        }
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        String dataStr = resultJson.getString("data");
        //QrCodeUtil.generate(resultStr, 300, 300, FileUtil.file("E:/qrcode.jpg"));
        BufferedImage bufferedImage = QrCodeUtil.generate(dataStr, 300, 300);
        //bufferedImage转化为图片base64
        try {
            return convertBufferedImageToBase64(bufferedImage, "png");
        } catch (Exception e) {
            log.info(e.getMessage());
            return "";
        }
    }

    @Override
    public String addVisitorPark(String carNumber, String appointmentTime) {
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("appId", "card_consume_system");
        tokenMap.put("clientSecret", "VE5ZSSL1HU58UJX4CN4W");
        String tokenResultStr = HttpUtil.post("http://111.14.222.51:8081/auth/client/token",tokenMap);
        if(StringUtils.isBlank(tokenResultStr)){
            return "访客停车失败";
        }
        JSONObject tokenResultJson = JSONObject.parseObject(tokenResultStr);
        int tokenCode = tokenResultJson.getInteger("code");
        if(tokenCode != 0){
            return "访客停车失败";
        }
        String accessToken = tokenResultJson.getString("access_token");
        JSONObject sendData = new JSONObject();
        sendData.put("park_code", "sdta0001");
        sendData.put("name", "ls");
        sendData.put("phone", "18574247841");
        sendData.put("appointment_time", appointmentTime);
        sendData.put("car_number", carNumber);
        sendData.put("units_inter", "通维");
        sendData.put("interviewees", "zs");
        sendData.put("interviewees_phone", "13157842287");
        sendData.put("card_currency", "1369553087085748225");
        sendData.put("pay_type", "0");
        sendData.put("effective_time", 1440);
        HttpResponse httpResponse = HttpUtil.createPost("http://111.14.222.51:8081/api/service/park/v1/add_visitor_park")
                .bearerAuth(accessToken)
                .body(sendData.toJSONString(), "application/json").execute();
        String resultStr = httpResponse.body();
        if(StringUtils.isBlank(resultStr)){
            return "";
        }
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        return resultJson.getString("data");
    }

    public static String convertBufferedImageToBase64(BufferedImage image, String formatName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, formatName, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}
